package cn.bbs.ba.util;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import cn.bbs.ba.db.ADaoOperate;

public class SqlStringUtil {

	/**
	 *
	 * @param sql
	 * @return zi duan
	 */
	public static List<String> getSQLFiled(String sql) {
		List<String> list = new ArrayList<String>();
		sql = sql.toUpperCase();
		String mapStr = "";
		String arrStr[] = sql.substring(6, sql.indexOf("FROM")).split(",");
		int cnt = arrStr.length;
		for (int i = 0; i < cnt; i ++) {
			mapStr = arrStr[i];
			if (mapStr.indexOf(" AS ") != -1) {
				mapStr = mapStr.split(" AS ")[1];
			}
			list.add(mapStr.trim());
		}
		return list;
	}

	/**
	 * @param kenSaku
	 * @return
	 * @throws SQLException
	 */
	public static String getSql(HashMap<String, String> kenSaku) throws SQLException {

		String sqlW = kenSaku.get(ADaoOperate.SQL_ID);
		String strArr[] = sqlW.split("\\?");
		int cnt = strArr.length;
		String strRet = "";
		if (cnt == 0) {
			return sqlW;
		}
		for (int i = 0; i < cnt; i = i + 2) {
			strRet = strRet +  strArr[i];
			if (i + 1 >= cnt) break;
			String field = kenSaku.get(strArr[i + 1].toUpperCase());
//			if (field == null) {
//				throw new SQLException();
//			}
			if (StringUtils.isEmpty(field) || "null".equals(field)) {
				strRet = strRet + "'" + "'" ;
			}
			else if (strArr[i + 1].equals("STARTROWS") || "ROWS".equals(strArr[i + 1])){
				strRet = strRet + field;
			}
			else {
				strRet = strRet + "'" + field + "'" ;
			}

		}
		return strRet;
	}
}
